package com.ashes.gateway.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;


@Configuration
public class CorsFilterConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        //1.创建CORS跨域资源共享策略(跨域规则)
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1.1 配置允许哪些域名跨域访问 * 开发阶段设置*允许所有的源头域名进行跨域访问 生产环境:设置为指定域名
        corsConfiguration.addAllowedOrigin("*");
        //1.2 配置允许源域名 发起请求类型 GET POST DELETE PUT OPTIONS
        corsConfiguration.addAllowedMethod("*");
        //1.3 配置允许源域名携带Cookie
        corsConfiguration.setAllowCredentials(true);
        //1.4 配置允许源域名携带请求头
        corsConfiguration.addAllowedHeader("*");
        //1.5 配置预检请求有效期
        corsConfiguration.setMaxAge(3600L);

        //2.配置规则,将规则作用经过网关所有请求
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(corsConfigurationSource);
    }
}
